package com.nuo.backend.modules.security.config;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.nuo.backend.common.utils.Constant;
import com.nuo.backend.common.utils.RedisUtils;
import com.nuo.backend.modules.security.entity.SecMenuEntity;
import com.nuo.backend.modules.security.entity.SecRoleEntity;
import com.nuo.backend.modules.security.service.SecMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * @description: TODO 根据用户传来的请求地址，分析出请求需要的角色
 * @author nuo
 * @date 2022/12/19 14:12
 * @version 1.0
 */
@Component
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    @Autowired
    SecMenuService secMenuService;

    @Autowired
    RedisUtils redisUtils;

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    private static final String[] URL_WHITELIST = {
            "/webjars/**",
            "/druid/**",
            "/storage/**",
            "/swagger/**",
            "/v2/api-docs",
            "/swagger-ui.html",
            "/swagger-resources/**",
            "/sys/**",
            "/captcha.jpg",
            "/test/**",
            "/user/**",
            "/sec/login",
            "/sec/register",
            "/sec/uuid",
            "/sec/captcha.jpg",
            "/sec/captchaStr"
    };

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {

        String requestUrl = ((FilterInvocation) object).getRequestUrl();

        // TODO 放行白名单
        for (String url : URL_WHITELIST) {
            if (antPathMatcher.match(url, requestUrl)) {
                return SecurityConfig.createList();
            }
        }

        // TODO 获取菜单 List
        String secMenuListStr = redisUtils.get(Constant.SEC_MENU_KEY);
        List<SecMenuEntity> secMenuList;
        if (StrUtil.isBlank(secMenuListStr)) {
            secMenuList = secMenuService.getSecMenuList();
            redisUtils.set(Constant.SEC_MENU_KEY, JSONArray.toJSONString(secMenuList));
        } else {
            secMenuList = JSONArray.parseArray(secMenuListStr).toJavaList(SecMenuEntity.class);
        }

        // TODO 获取需要的角色
        for (SecMenuEntity secMenu : secMenuList) {
            if (antPathMatcher.match(secMenu.getUrl(), requestUrl)) {
                List<SecRoleEntity> secRoleList = secMenu.getSecRoleList();
                String[] str = new String[secRoleList.size()];
                for (int i = 0; i < secRoleList.size(); i++) {
                    str[i] = "ROLE_" + secRoleList.get(i).getRoleName();
                }
                return SecurityConfig.createList(str);
            }
        }

        // TODO 默认未设定则需要 root 最高权限
        return SecurityConfig.createList("ROLE_root");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
